package mesweb.mesweb.controller.procedure;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.farvision.common.api.CommonResult;
import com.farvision.common.exception.ApiException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import mesweb.mesweb.dto.Procedure.MesProductProcedureBranchDto;
import mesweb.mesweb.entity.Procedure.MesProductProcedureBranch;
import mesweb.mesweb.entity.Procedure.ModelProductLineBranchProcedureLine;
import mesweb.mesweb.service.procedure.IMesProductProcedureBranchService;
import mesweb.mesweb.service.procedure.IMesProductProcedureService;
import mesweb.mesweb.service.procedure.IModelProductLineBranchProcedureLineService;
import mesweb.mesweb.vo.procecdure.MesProductProcedureBranchVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * @Description: 生产工序分支
 * @Author: jeecg-boot
 * @Date: 2021-06-26
 * @Version: V1.0
 */

@Api(tags = "生产工序分支")
@RestController
@RequestMapping("/mes/mesProductProcedureBranch")
public class MesProductProcedureBranchController {
    @Autowired
    private IMesProductProcedureBranchService mesProductProcedureBranchService;

    @Autowired
    private IMesProductProcedureService mesProductProcedureService;

    @Autowired
    private IModelProductLineBranchProcedureLineService modelProductLineBranchProcedureLineService;

    @GetMapping("/GetAll")
    @ApiOperation("获取全部数据列表")
    public CommonResult<?> GetAll(@ApiParam("名称") @RequestParam(value = "name", required = false) String name) {
        List<MesProductProcedureBranchVo> data = new ArrayList<>();
        QueryWrapper<MesProductProcedureBranchVo> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isBlank(name) || name.equals("全部")) {
        }
        data = mesProductProcedureBranchService.getProductProcedureBranch(queryWrapper);
        return CommonResult.success(data);
    }

    /**
     * 分页列表查询
     *
     * @param mesProductProcedureBranch
     * @param page
     * @param size
     * @param req
     * @return
     */
    @ApiOperation(value = "生产工序分支-分页列表查询", notes = "生产工序分支-分页列表查询")
    @GetMapping(value = "/list")
    public CommonResult<?> queryPageList(MesProductProcedureBranchVo mesProductProcedureBranch,
                                         @RequestParam(name = "page", defaultValue = "1") Integer page,
                                         @RequestParam(name = "size", defaultValue = "10") Integer size,
                                         HttpServletRequest req) {
        QueryWrapper<MesProductProcedureBranchVo> queryWrapper = new QueryWrapper<>();
        Page<MesProductProcedureBranchVo> pageMesProductProcedureBranchVo = new Page<MesProductProcedureBranchVo>(page, size);
        IPage<MesProductProcedureBranchVo> pageList = mesProductProcedureBranchService.getProductProcedureBranch(pageMesProductProcedureBranchVo, queryWrapper);
        return CommonResult.success(pageList);
    }

    /**
     * 编辑
     *
     * @param mesProductProcedureBranch
     * @return
     */
    @ApiOperation(value = "生产工序分支-编辑", notes = "生产工序分支-编辑")
    @PostMapping(value = "/save")
    @Transactional
    public CommonResult<?> edit(@RequestBody MesProductProcedureBranch mesProductProcedureBranch) {

        boolean result = false;
        if (mesProductProcedureBranch.getId() == 0L) {
            QueryWrapper<MesProductProcedureBranch> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("product_line_branch_no", mesProductProcedureBranch.getProductProcedureBranchNo());
            queryWrapper.or().eq("product_line_branch_name", mesProductProcedureBranch.getProductProcedureBranchName());
            MesProductProcedureBranch mesTechnologyFlow1 = mesProductProcedureBranchService.getOne(queryWrapper);
            if (mesTechnologyFlow1 != null) {
                String msg = StrUtil.format("编号{}或名称{}已经存在！", mesTechnologyFlow1.getProductProcedureBranchNo(), mesTechnologyFlow1.getProductProcedureBranchName());
                throw new ApiException(msg);
            }
            result = mesProductProcedureBranchService.save(mesProductProcedureBranch);
        } else {
            result = mesProductProcedureBranchService.updateById(mesProductProcedureBranch);
        }

        HashSet<Long> hashSet = new HashSet<>();
        modelProductLineBranchProcedureLineService.list().stream().filter((o) -> {
            return o.getProductProcedureBranchId().equals(mesProductProcedureBranch.getId());
        }).map(o -> hashSet.add(o.getProcedureLineId()));

        //更新瓶颈工序的id,名称和标准工时
        if (hashSet.size() > 0) {
            mesProductProcedureService.updateBottleneckProcedure(hashSet.iterator().next());
        }
        return CommonResult.success(mesProductProcedureBranch);
    }

    /**
     * 编辑
     *
     * @param mesProductProcedureBranchDto
     * @return
     */
    @ApiOperation(value = "生产工序-编辑", notes = "生产工序-编辑")
    @PostMapping(value = "/saveRelation")
    public CommonResult<?> saveRelation(@RequestBody MesProductProcedureBranchDto mesProductProcedureBranchDto) {
        boolean result = false;
        MesProductProcedureBranch mesProductProcedureBranch = new MesProductProcedureBranch();
        BeanUtils.copyProperties(mesProductProcedureBranchDto, mesProductProcedureBranch);
        if (mesProductProcedureBranchDto.getId() == 0L) {
            result = mesProductProcedureBranchService.save(mesProductProcedureBranch);
        } else {
            result = mesProductProcedureBranchService.updateById(mesProductProcedureBranch);
        }

        ModelProductLineBranchProcedureLine modelProductLineBranchProcedureLine = new ModelProductLineBranchProcedureLine();
        modelProductLineBranchProcedureLine.setProcedureLineId(mesProductProcedureBranchDto.getProductProcedureLineId());
        modelProductLineBranchProcedureLine.setProductProcedureBranchId(mesProductProcedureBranch.getId());

        if (mesProductProcedureBranchDto.getRelationId() != null && mesProductProcedureBranchDto.getRelationId() > 0) {
            modelProductLineBranchProcedureLine.setId(mesProductProcedureBranchDto.getRelationId());
            result = modelProductLineBranchProcedureLineService.updateById(modelProductLineBranchProcedureLine);
        } else {
            result = modelProductLineBranchProcedureLineService.save(modelProductLineBranchProcedureLine);
        }

        //更新瓶頸工序和标准工时
        mesProductProcedureService.updateBottleneckProcedure(mesProductProcedureBranchDto.getProductProcedureLineId());

        return CommonResult.success(modelProductLineBranchProcedureLine);
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "生产工序分支-通过id删除", notes = "生产工序分支-通过id删除")
    @DeleteMapping(value = "/delete")
    @Transactional
    public CommonResult<?> delete(@RequestParam(name = "id", required = true) String id) {
        MesProductProcedureBranch mesProductProcedureBranch = mesProductProcedureBranchService.getById(id);
        mesProductProcedureBranchService.removeById(id);
        HashSet<Long> hashSet = new HashSet<>();
        modelProductLineBranchProcedureLineService.list().stream().filter((o) -> {
            return o.getProductProcedureBranchId().equals(id);
        }).map(o -> hashSet.add(o.getProcedureLineId()));

        //更新瓶颈工序的id,名称和标准工时
        if (mesProductProcedureBranch != null && hashSet.size() > 0) {
            mesProductProcedureService.updateBottleneckProcedure(hashSet.iterator().next());
        }
        return CommonResult.success("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "生产工序分支-批量删除", notes = "生产工序分支-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    @Transactional(rollbackFor = Throwable.class)
    public CommonResult<?> deleteBatch(@ApiParam("MesProductProcedureBranchIDs") @RequestBody List<Long> ids) {


        //更新瓶颈工序的id,名称和标准工时
        HashSet<Long> hashSet = new HashSet<>();
        modelProductLineBranchProcedureLineService.list().stream().filter( o -> { return ids.contains(o.getProductProcedureBranchId());}).map( o -> {
               return  mesProductProcedureService.updateBottleneckProcedure(o.getProcedureLineId());
        });
        this.mesProductProcedureBranchService.removeByIds(ids);
        return CommonResult.success("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "生产工序分支-通过id查询", notes = "生产工序分支-通过id查询")
    @GetMapping(value = "/queryById")
    public CommonResult<?> queryById(@RequestParam(name = "id", required = true) String id) {
        MesProductProcedureBranch mesProductProcedureBranch = mesProductProcedureBranchService.getById(id);
        return CommonResult.success(mesProductProcedureBranch);
    }
}
